import json
import datetime
from decimal import Decimal
import pytz


class DataConverter:
    """
    数据转换工具类，处理各种数据类型的转换和格式化
    """

    @staticmethod
    def convert_datetime_to_utc(dt):
        """
        将 datetime 对象转换为 UTC 字符串
        :param dt: datetime 对象
        :return: UTC 格式字符串 (e.g. "2023-01-01T12:00:00.000Z")
        """
        if not isinstance(dt, datetime.datetime):
            return dt

        tz_shanghai = pytz.timezone('Asia/Shanghai')
        utc_format = "%Y-%m-%dT%H:%M:%S.000Z"
        shanghai_time_localized = tz_shanghai.localize(dt)  # 时间本地化
        utc_time = shanghai_time_localized.astimezone(pytz.utc)  # 时区转换
        return utc_time.strftime(utc_format)

    @staticmethod
    def convert_value(value):
        """
        转换值为适合 JSON 的格式
        :param value: 需要转换的值
        :return: 转换后的值
        """
        if isinstance(value, datetime.datetime):
            return DataConverter.convert_datetime_to_utc(value)
        elif isinstance(value, Decimal):
            return str(value)
        return value

    @staticmethod
    def convert_item(item):
        """
        转换单个数据项
        :param item: 原始数据项 (dict)
        :return: 转换后的数据项
        """
        new_item = {}
        for key, value in item.items():
            new_item[key] = {'value': DataConverter.convert_value(value)}
        if 'phone' in new_item:
            new_item['name'] = {'value': new_item['phone']['value']}
        return new_item


class DateTimeJSONEncoder(json.JSONEncoder):
    """
    自定义JSON编码器，处理datetime和Decimal类型
    """
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return DataConverter.convert_datetime_to_utc(obj)
        elif isinstance(obj, Decimal):
            return str(obj)
        return super().default(obj)


# 使用示例
if __name__ == '__main__':
    # 测试时间转换
    now = datetime.datetime.now()
    print("当前时间UTC格式:", DataConverter.convert_datetime_to_utc(now))

    # 测试数据项转换
    test_data = {
        'id': 1,
        'name': '测试',
        'phone': '13800138000',
        'amount': Decimal('100.50'),
        'create_time': now
    }
    print("转换后的数据项:", DataConverter.convert_item(test_data))

    # 测试JSON编码
    print("JSON编码结果:", json.dumps(test_data, cls=DateTimeJSONEncoder, ensure_ascii=False))